package org.chuan.auth.service.impl;

import org.chuan.auth.domain.Permission;
import org.chuan.auth.domain.Role;
import org.chuan.auth.domain.RolePermission;
import org.chuan.auth.dto.RoleDto;
import org.chuan.auth.mapper.PermissionMapper;
import org.chuan.auth.mapper.RolePermissionMapper;
import org.chuan.auth.service.IRoleService;
import org.chuan.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2024-04-07
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void addOrUpfate(RoleDto roleDto) {
        Role role = roleDto.getRole();
        if (role.getId() != null){
            super.update(role);
        }else {
            super.save(role);
        }
        // 维护中间表数据
        rolePermissionMapper.deleteByRoleId(role.getId());
        // 重新维护关联关系
        List<Permission> permissions = permissionMapper.queryByIds(roleDto.getPermissionIds());
        List<RolePermission> list = new ArrayList<>();
        for (Permission permission : permissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setPermissionSn(permission.getSn());
            list.add(rolePermission);
        }
        rolePermissionMapper.batchSave(list);
    }

    @Override
    public List<Long> queryPermissionId(Long id) {
        return rolePermissionMapper.queryPermissionId(id);
    }
}
